package com.jlz.service.email;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;

import com.julewa.Configuration;

@Component
public class BinaryResources {
	
	private @Autowired Configuration conf = null;
	private Map<String, byte[]> resources = new HashMap<String, byte[]>();
	private ClassLoader classloader = BinaryResources.class.getClassLoader();
	
	public byte[] getBinary(String id){
		byte[] rs = resources.get(id);
		if(rs != null)return rs;
		if(resources.containsKey(id))return null;
		String path = "binary." + id;
		path = conf.getProperty(path, "").trim();
		if("".equals(path)){
			resources.put(id, null);
			return null;
		}
		InputStream in = classloader.getResourceAsStream(path);
		if(in == null){
			resources.put(id, null);
			return null;
		}
		try{
			rs = new byte[in.available()];
			in.read(rs);
			in.close();
		}catch(Exception e){
			e.printStackTrace();
		}
		resources.put(id, rs);
		return rs;
	}
	
	public Resource getResource(String id){
		byte[] rs = getBinary(id);
		if(rs == null)return null;
		return (new ByteArrayResource(rs){
			private String fname;
			public String getFilename() {
				return fname;
			};
			ByteArrayResource init(String id){
				fname = id;
				return this;
			}
		}).init(id);
	}
	
}
